package org.jdcenter.rmi.impl;

import java.rmi.RemoteException;
import java.util.logging.Logger;

import static org.jdcenter.rmi.impl.Glossary.handler;

import org.jdcenter.rmi.abs.*;

public class HandlerChannel implements Channel {
    private static Logger aLogger = Logger.getLogger(HandlerChannel.class.getCanonicalName());
    private Logger getLogger() {
        return aLogger;
    }

    private int cookie;
    private RpcHandler handler;
    private HandlerChannelCache cache;

    public HandlerChannel(RpcHandler handler) {
        this.handler = handler;
    }

    public void setHandler(RpcHandler handler) {
        this.handler = handler;
    }

    public void setIdentity(HandlerChannelCache cache, int cookie) {
        this.cache = cache;
        this.cookie = cookie;
    }

    public Object invoke(String method,Object[] args,Object result) throws ChannelException, HandlerException {
        try {
            getLogger().finest("Server|" + handler(cookie) + " ==> " + args);
            return handler.callback(result);
        } catch (RemoteException e) {
            this.cache.reject(cookie);
            throw new ChannelException(e);
        }
    }
}

